#!/usr/bin/env python
import os
from google.appengine.ext import webapp
from google.appengine.ext.webapp import util, template
from google.appengine.api import users

from gaesessions import SessionMiddleware
from models import Quote

def transform(value):
    try:
        return int(value)
    except ValueError:
        try:
            return float(value)
        except ValueError:
            try:
                return complex(value)
            except ValueError:
                return value

class DataProxy:
    def last_option_quotes(self):
        return Quote.all().filter("is_last =", True).filter("type =", "O")

    def user_nickname(self):
        user = users.get_current_user()
        return user.nickname()

    def logout_url(self):
        return users.create_logout_url("/")

# Handler do przetwarzania szablonow
class TemplateHandler(webapp.RequestHandler):
    def get(self):
        if self.request.path == '/':
            template_file = 'templates/index.html'
        else:
            template_file = 'templates'+self.request.path

        template_values = {
            'data': DataProxy()
        }

        self.response.out.write(template.render(template_file, template_values))

class GatewayHandler(webapp.RequestHandler):
    def get(self, service_name, method_name):
        # Pobranie argumentow z zadania:
        arg_names = self.request.arguments()
        arguments = { }
        for arg_name in arg_names:
            # Zamiana listy z jednym elementem na jeden element
            tmp = self.request.get_all(arg_name)
            if len(tmp) == 1:
                # Transformacja parametru do poprawnego typu
                value = transform(tmp[0])
            else:
                # Transformacja parametrow do poprawnych typow
                value = []
                for val in tmp:
                    value.append(transform(val))

            # Zapisanie wartosci w slowniku
            arguments[arg_name] = value
        
        # Zaimportowanie klasy
        class_name = service_name.lower().capitalize()+'Service'
        package = __import__('services.'+service_name, globals(), locals(), [class_name])
        
        # Utworzenie obiektu klasy uslugi:
        service_obj = eval("package."+class_name+"()")
        # Pobranie metody serwisu:
        method = getattr(service_obj, method_name)
        # Wywolanie metody:
        result = method(arguments)
    
        self.response.out.write(result)
        
def main():
    app = webapp.WSGIApplication([(r'/(?:[a-zA-Z0-9_\-]+\.html)?', TemplateHandler),
                                  (r'/gateway/([a-zA-Z0-9_\-]+)/([a-zA-Z0-9_\-]+)', GatewayHandler)], debug=True)
    app = SessionMiddleware(app, cookie_key="04f7cb0668cdf1b8b056c9071c57393bff51baec6d2074ff5f53685df73fcb43")
    util.run_wsgi_app(app)

if __name__ == '__main__':
    main()
